import { increment, decrement, incrementAsync } from '../../redux/actions/count'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
import React, { Component } from 'react'
import { Button, Select } from 'antd'

const { Option } = Select
class Count extends Component {
  state = { count: 0 }
  selectNumber = 1

  add = () => {
    this.props.increment(this.selectNumber)
  }

  decrement = () => {
    this.props.decrement(this.selectNumber)
  }

  oddAdd = () => {
    if (this.props.count % 2 === 1) {
      this.props.increment(this.selectNumber)
    }
  }

  asyncAdd = () => {
    this.props.incrementAsync(this.selectNumber, 500)
  }

  selectChange = (value) => {
    this.selectNumber = value
  }

  render() {
    return (
      <div>
        Count:当前求和为：{this.props.count}
        <br />
        Count:下方总人数：{this.props.personCount}
        <br />
        <Select
          showSearch
          style={{ width: 200 }}
          placeholder="选择加多少个"
          onChange={this.selectChange}
          optionFilterProp="children"
          defaultValue={this.selectNumber}
          filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
        >
          <Option value="1">1</Option>
          <Option value="2">2</Option>
          <Option value="3">3</Option>
        </Select>
        <Button onClick={this.add}>+</Button>
        <Button onClick={this.decrement}>-</Button>
        <Button onClick={this.oddAdd}>当前求和为奇数再加</Button>
        <Button onClick={this.asyncAdd}>异步加</Button>
      </div>
    )
  }
}

// a函数的返回对象，作为状态传递给了UI组件。

// 创建并暴露一个Count的容器组件
export default connect(
  (state) => {
    // 等价于<CountUI n={900} />
    return { count: state.count, personCount: state.persons.length }
  },
  // (dispatch) => {
  //   return {
  //     increment: (number) => {
  //       dispatch(increment(number))
  //     },
  //     decrement: (number) => {
  //       dispatch(decrement(number))
  //     },
  //     incrementAsync: (number, time) => {
  //       dispatch(incrementAsync(number, time))
  //     }
  //   }
  // }
  // 简写方式
  // react-redux自动分发
  {
    increment,
    decrement,
    incrementAsync
  }
)(Count)
